// eslint-disable-next-line
import * as loginService from '../api/login'
import store from "@/store";
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView, InnerMenu } from '../layouts'
import finance from './finance'
import inventory from './inventory'
import purchase from './purchase'
import sale from './sale'
import production from './production'
import integration from './integration'
import inventoryCheck from './inventoryCheck'
import hr from "./hr"
import research from './research'
import website from './website'
import app from './app'
import contract from './contract'
import project from './project'
import analysis from './analysis';
import message from './message';
import call from './call';


export const constantRouterComponentsKeys = () => {
    return Object.keys(constantRouterComponents)
};
// 前端路由表
const constantRouterComponents = {
    ...finance,
    ...analysis,
    ...inventory,
    ...purchase,
    ...sale,
    ...production,
    ...integration,
    ...inventoryCheck,
    ...hr,
    ...research,
    ...website,
    ...app,
    ...contract,
    ...project,
    ...message,
    ...call,
    // 基础页面 layout 必须引入
    BasicLayout: BasicLayout,
    BlankLayout: BlankLayout,
    RouteView: RouteView,
    PageView: PageView,
    InnerMenu: InnerMenu,
    "403": () =>
        import( /* webpackChunkName: "error" */ "@/views/exception/403"),
    "404": () =>
        import( /* webpackChunkName: "error" */ "@/views/exception/404"),
    "500": () =>
        import( /* webpackChunkName: "error" */ "@/views/exception/500"),
    //限制 使用
    Limit: () =>
        import("@/views/exception/limit"),
    // // 你需要动态引入的页面组件
    Workplace: () =>
        import("@/views/dashboard/Workplace"),
    // Analysis: () => import("@/views/dashboard/Analysis"),

    //菜单管理
    MenuManagerList: () =>
        import("@/views/system/menu/list"),
    //模块管理
    ModuelManagerList: () =>
        import("@/views/system/moduel/list"),
    //日志管理
    LogManagerList: () =>
        import("@/views/system/log/list"),
    //用户管理
    UserManagerList: () =>
        import("@/views/system/user/list"),
    //机构管理
    OfficeManagerList: () =>
        import("@/views/system/office/list"),
    //角色管理
    RoleManagerList: () =>
        import("@/views/system/role/list"),
    //地区管理
    AreaManagerList: () =>
        import("@/views/system/area/list"),
    //字典类型管理
    DictTypeManagerList: () =>
        import("@/views/system/dictManager/dictType/list"),
    //字典数据管理
    DictDataManagerList: () =>
        import("@/views/system/dictManager/dictData/list"),

    //字典维护
    DictDetails: () =>
        import("@/views/system/dictManager/dictDetails/list"),

    //审批流程管理
    ApprovalProcess: () =>
        import("@/views/system/approvalProcess/list"),
    //基本信息
    CompanyInfo: () =>
        import("@/views/system/info/companyInfo"),
    //网站相关配置
    WebConfig: () =>
        import("@/views/system/config/webConfig"),
    //提现打款
    WithdrawalPayment: () =>
        import("@/views/system/withdrawal/withdrawalPayment"),
    //应用商城
    GoodsInfo: () =>
        import("@/views/system/goods/list"),
    //财务信息
    OrderInfo: () =>
        import("@/views/system/order/list"),
    //协议管理
    Agreement: () =>
        import("@/views/system/agreement/list"),

    //公海客户管理
    CrmCustomerList: () =>
        import("@/views/crm/customer/list"),
    //潜在客户管理
    CrmPotential: () =>
        import("@/views/crm/customer/potential"),
    //成交客户管理
    CrmDeals: () =>
        import("@/views/crm/customer/deals"),

    //联系人
    CrmlinkMan: () =>
        import("@/views/crm/linkMan/list"),
    //联系记录
    CrmTouch: () =>
        import("@/views/crm/touch/list"),

    //客户详情
    CrmDetail: () =>
        import("@/views/crm/customer/detail"),
    //自定义设置
    //客户策略
    CRMStrategy: () =>
        import("@/views/crm/customize/strategy"),
    //客户编码
    CRMCode: () =>
        import("@/views/crm/customize/codeSet"),
    //客户自定义字段
    CRMCustomerSet: () =>
        import("@/views/crm/customize/customerSet"),


    //联系人自定义
    CRMLinkManSet: () =>
        import("@/views/crm/customize/linkManSet"),
    //联系记录自定义
    CRMTouchSet: () =>
        import("@/views/crm/customize/touchSet"),
    //商机自定义字段
    CRMBusinessSet: () =>
        import("@/views/crm/customize/businessSet"),
    //合同自定义字段
    CRMContractSet: () =>
        import("@/views/crm/customize/contractSet"),
    //报价单
    CrmQuotedPrice: () =>
        import("@/views/crm/price/list"),
    //收货人信息
    CrmConsignee: () =>
        import("@/views/crm/consignee/list"),
    //财务信息
    CrmFinance: () =>
        import("@/views/crm/finance/list"),
    //商机描述
    CrmBusiness: () =>
        import("@/views/crm/business/list"),
    //销售漏斗
    CrmSaleFunnel: () =>
        import("@/views/crm/business/salefunnel"),
    //需求管理
    CrmRequirement: () =>
        import("@/views/crm/requirement/list"),
    //客户文档
    CrmFiles: () =>
        import("@/views/crm/files/list"),


    //市场活动
    CrmActivity: () =>
        import("@/views/crm/activity/list"),
    //活动邀请模板
    CrmInviteTemplate: () =>
        import("@/views/crm/activity/template"),
    //活动邀请列表
    CrmInviteList: () =>
        import("@/views/crm/activity/inviteList"),


    //报表与分析
    CrmStatistics: () =>
        import("@/views/crm/statistics/reportForm"),
    //合同模版管理
    CrmContractTemplate: () =>
        import("@/views/crm/contract/templateList"),
    //合同管理
    CrmContract: () =>
        import("@/views/crm/contract/list"),

    //审核流程
    Approval: () =>
        import("@/views/work/approval/list"),

    //个人中心-基本信息
    UserInfo: () =>
        import("@/views/personal/userInfo"),
    //个人分享
    UserShare: () =>
        import("@/views/personal/userShare"),
    MemberInfo: () =>
        import("@/views/personal/memberInfo"),
    //我的佣金
    UserCommission: () =>
        import("@/views/personal/userCommission"),
    //我的订单
    UserOrder: () => import("@/views/personal/userOrder"),
    //个人资料
    PersonalData: () =>
        import("@/views/personal/personalData"),
    //便签
    UserNote: () =>
        import("@/views/personal/userNote"),
    //我的笔记
    MyNote: () =>
        import("@/views/personal/myNote"),

    //租户管理-租户列表
    MemberTenant: () =>
        import("@/views/member/tenant/list"),
    //商品管理
    MemberGoods: () =>
        import("@/views/member/goods/list"),
    //推客等级
    MemberTwitter: () =>
        import("@/views/member/twitter/list"),
    //订单管理
    MemberOrder: () =>
        import("@/views/member/order/list"),
    //财务管理
    MemberFinance: () =>
        import("@/views/member/finance/list"),
    //密钥管理
    MemberSecretKey: () =>
        import("@/views/member/secretKey/list"),
    //商品配置
    GoodsConfig: () =>
        import("@/views/member/goodsConfig/list"),

    //办公 工作报表
    workReportForm: () =>
        import("@/views/work/reportForm/list"),
    //工作计划
    workPlan: () =>
        import("@/views/work/plan/list"),
    //工作总结
    workSummary: () =>
        import("@/views/work/summary/list"),
    //基础设置
    workSet: () =>
        import("@/views/work/set/list")
};

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
    path: "*",
    redirect: "/404",
    hidden: true
};
// //外呼工具条 路由
// const callToolBarRouter = {
//     path: "../../../public/XyCallToolBar/index.html",
//     hidden: true
// };

// 个人中心
const pasersonalRouter = {
    path: "/personal",
    component: "RouteView",
    redirect: "/views/personal/userInfo",
    children: [
        // {
        //     path: "/views/personal/userInfo",
        //     name: "基本信息",
        //     component: "UserInfo",
        //     meta: {
        //         title: "基本信息",
        //         icon: "far fa-id-card nav-icon",
        //         keepAlive: true,
        //         permission: null,
        //         target: null,
        //     },
        //     id: 244,
        //     isShow: true,
        //     key: "基本信息",
        //     menuType: 1,
        // },
        {
            path: "/views/personal/userShare",
            name: "推广商品",
            component: "UserShare",
            meta: {
                title: "推广商品",
                icon: "fas fa-share-alt nav-icon",
                keepAlive: true,
                permission: null,
                target: null,
            },
            id: 245,
            isShow: true,
            key: "推广商品",
            lallalalal: 11111,
            menuType: 1,
        },
        /** 开始 屏蔽 */
        {
            path: "/views/personal/memberInfo",
            name: "客户管理",
            component: "MemberInfo",
            meta: {
                title: "客户管理",
                icon: "fas fa-user-alt nav-icon",
                keepAlive: true,
                permission: null,
                target: null,
            },
            id: 2499,
            isShow: true,
            key: "客户管理",
            menuType: 1,
        },
        {
            path: "/views/personal/userCommission",
            name: "我的收益",
            component: "UserCommission",
            meta: {
                title: "我的收益",
                icon: "fas fa-yen-sign nav-icon",
                keepAlive: true,
                permission: null,
                target: null,
            },
            id: 246,
            isShow: true,
            key: "我的收益",
            menuType: 1,
        },
        // {
        //     path: "/views/personal/UserOrder",
        //     name: "我的订单",
        //     component: "UserOrder",
        //     meta: {
        //         title: "我的订单",
        //         icon: "fas fa-file nav-icon",
        //         keepAlive: true,
        //         permission: null,
        //         target: null,
        //     },
        //     id: 2461,
        //     isShow: true,
        //     key: "我的订单",
        //     menuType: 1,
        // },
        {
            path: "/views/personal/userNote",
            name: "记事本",
            component: "UserNote",
            meta: {
                title: "记事本",
                icon: "fas fa-file nav-icon",
                keepAlive: true,
                permission: null,
                target: null,
            },
            id: 99901,
            isShow: true,
            key: "记事本",
            menuType: 1,
        },
        // {
        //     path: "/views/personal/myNote",
        //     component: "MyNote",
        //     name: "我的笔记",
        //     meta: {
        //         title: "我的笔记",
        //         icon: "fas fa",
        //         keepAlive: true,
        //         permission: null,
        //         target: null,
        //     },
        //     id: 99902,
        //     isShow: true,
        //     key: "我的笔记",
        //     menuType: 1,
        // },
        /** 结束 屏蔽 */
        {
            name: "设置",
            component: "RouteView",
            meta: {
                title: "设置",
                icon: "fa fa-cog nav-icon",
                keepAlive: true,
                permission: null,
                target: null,
            },
            id: 245,
            isShow: true,
            key: "设置",
            menuType: 1,
            children: [{
                path: "/views/personal/userInfo",
                name: "账户信息",
                component: "UserInfo",
                meta: {
                    title: "账户信息",
                    icon: "far fa-id-card nav-icon",
                    keepAlive: true,
                    permission: null,
                    target: null,
                },
                id: 244,
                isShow: true,
                key: "账户信息",
                menuType: 1,
            },
            {
                path: "/views/personal/personalData",
                component: "PersonalData",
                name: "基本信息",
                meta: {
                    title: "基本信息",
                    keepAlive: true,
                    permission: null,
                    target: null,
                    icon: "fas fa-user-alt nav-icon",
                },
                id: 99999,
                isShow: true,
                key: "基本信息",
                menuType: 1,
            },
            ]
        },
    ],
    meta: {
        title: "个人中心",
        icon: "fa fa-user",
        keepAlive: true,
        permission: null,
        target: null,
    },
    menuType: 1,
    id: 243,
    isShow: true,
    key: "个人中心",
    name: "个人中心",
}

//消息中心
const messageRouter = {
    path: "/personal",
    component: "RouteView",
    redirect: "/views/message/list",
    children: [
        {
            path: "/views/message/list",
            name: "消息列表",
            component: "MessageList",
            meta: {
                title: "消息列表",
                icon: "far fa-list-alt nav-icon",
                keepAlive: true,
                permission: null,
                target: null,
            },
            id: 8801,
            isShow: true,
            key: "消息列表",
            menuType: 1,
        },
    ],
    meta: {
        title: "消息中心",
        icon: "fa fa-bullhorn",
        keepAlive: true,
        permission: null,
        target: null,
    },
    menuType: 1,
    id: 8800,
    isShow: true,
    key: "消息中心",
    name: "消息中心",
}

//客户详情（需要单独处理）
const crmDetailRouter = {
    path: "/crm/customer/detail/:customerName/:customerId/:activeKey",
    component: "CrmDetail",
    redirect: null,
    meta: {
        title: "客户详情",
        icon: "far fa-circle nav-icon",
        keepAlive: true,
        permission: null,
        target: null,
    },
    menuType: 1,
    parentId: 0,
    id: 10000,
    isShow: false,
    key: "客户详情",
    name: "客户详情",
}

// 根级菜单
const rootRouter = {
    key: "",
    name: "index",
    path: "",
    component: "BasicLayout",
    redirect: "/dashboard",
    meta: {
        title: "首页"
    },
    children: []
};



/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
    return new Promise((resolve, reject) => {
        loginService
            .getCurrentUserNav(token)
            .then(res => {
                const menuRoot = { ...rootRouter };
                const { data } = res;
                const menuNav = [];
                const menuChildrenNav = [];
                //筛选 可见的菜单，不可见的会被处理成二级路由
                let menuData = data.filter(f => f.isShow);
                //筛选 路由
                let filterRouters = data.filter(f => (f.menuType == 1 || f.menuType == 3));
                let menusMap = new Map();
                menuData.forEach(item => {
                    if (item.path) {
                        menusMap.set(item.path, item);
                    }
                });
                store.commit("SET_MENUS_MAP", menusMap);
                //后端数据, 根级树数组, 根级 PID
                listToMenuTree(menuData, menuChildrenNav, 0);
                menuRoot.children = menuChildrenNav;
                menuRoot.children.push(messageRouter);
                menuRoot.children.push(pasersonalRouter);
                menuNav.push(menuRoot);
                store.commit("SET_MENUS", menuNav);

                const routerChildrenNav = [];
                listToRouterTree(filterRouters, routerChildrenNav, 0);
                //特殊处理 “客户详情”路由
                let customerRouter = routerChildrenNav.find(f => f.path == '/crm/customer');
                if (customerRouter) customerRouter.children.push(crmDetailRouter);
                rootRouter.children = routerChildrenNav;
                rootRouter.children.push(messageRouter);
                rootRouter.children.push(pasersonalRouter);

                const routers = generator([rootRouter]);
                routers.push(notFoundRouter);
                // routers.push(callToolBarRouter);

                resolve(routers);
            })
            .catch(err => {
                reject(err);
            });
    });
};

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
    return routerMap.map(item => {
        const { title, show, hideChildren, hiddenHeaderContent, target, icon } =
            item.meta || {};

        const currentRouter = {
            // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
            path: item.path || `${(parent && parent.path) || ""}/${item.key}`,
            // 路由名称，建议唯一
            name: item.name + item.id,
            // 该路由对应页面的 组件 :方案1
            // component: constantRouterComponents[item.component || item.key],
            // 该路由对应页面的 组件 :方案2 (动态加载)
            component: constantRouterComponents[item.component || item.key] ||
                (() =>
                    import(`@/views/${item.component}`)),

            // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
            id: item.id,
            meta: {
                name: item.name,
                parentIds: item.parentIds,
                isShow: item.isShow,
                menuType: item.menuType,
                id: item.id,
                key: item.parentId + "_" + item.id,
                title: title,
                icon: icon || undefined,
                hiddenHeaderContent: hiddenHeaderContent,
                target: target,
                permission: item.name
            }
        };

        // 是否设置了隐藏菜单
        if (show === false) {
            currentRouter.hidden = true;
        }
        // 是否设置了隐藏子菜单
        if (hideChildren) {
            currentRouter.hideChildrenInMenu = true;
        }
        // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
        if (!currentRouter.path.startsWith("http")) {
            currentRouter.path = currentRouter.path.replace("//", "/");
        }
        // 重定向
        item.redirect &&
            item.redirect != item.path &&
            (currentRouter.redirect = item.redirect);
        // 是否有子菜单，并递归处理
        if (item.children && item.children.length > 0) {
            // Recursion
            currentRouter.children = generator(item.children, currentRouter);
        }
        return currentRouter;
    });
};

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToMenuTree = (list, tree, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId && item.menuType == 1) {
            const child = {
                ...item,
                key: item.key || item.name,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            listToMenuTree(list, child.children, child.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            tree.push(child);
        }
    });
};

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToRouterTree = (list, tree, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId && item.menuType != 2) {
            const child = {
                ...item,
                key: item.key || item.name,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            listToRouterTree(list, child.children, child.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            tree.push(child);
        }
    });
};